package com.hmall.cart.config;

import com.hmall.common.utils.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

/**
 * ClassName: MqUserInfoConfig
 * Package:
 * Description
 *
 * @Author xw
 * @Create 2023/12/15 20:35
 */

@Slf4j
@Configuration
public class MqUserInfoConfig {


    @Autowired
    private SimpleRabbitListenerContainerFactory SimpleRabbitListenerContainerFactory;


    @PostConstruct
    public void initListener() {
        /*
         * 监听rabbitmq的消息接受，检查每一条消息，如果有user-info 就存到ThreadLocal中
         *  这样内部都可以使用user-info
         * */

        SimpleRabbitListenerContainerFactory.setAfterReceivePostProcessors(
                new MessagePostProcessor() {
                    @Override
                    public Message postProcessMessage(Message message) throws AmqpException {


                        Long userID = message.getMessageProperties().getHeader("user-info");

                        System.out.println("mq 消息监听到 userId： " + userID);
                        if (userID != null) {

                            UserContext.setUser(userID);

                        }

                        return message;
                    }
                }
        );

    }
}
